package com.sdry.web.controller.jyy;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.sdry.model.hpf.Product;
import com.sdry.model.jyy.Cut;
import com.sdry.model.jyy.CutExample;
import com.sdry.model.jyy.CutExample.Criteria;
import com.sdry.model.jyy.Solid;
import com.sdry.model.jyy.SolidExample;
import com.sdry.model.llm.Team;
import com.sdry.model.llm.User;
import com.sdry.model.zc.ZcTrolleyBindingEntity;
import com.sdry.service.jyy.CutServise;
import com.sdry.service.jyy.ShedudetailServise;
import com.sdry.service.jyy.SolidServise;
import com.sdry.utils.DateUtil;
import com.sdry.utils.ResponseUtil;

/**
 * @ClassName:    [CutController]   
 * @Description:  [切割  工位  Controller]   
 * @Author:       [jyy]   
 * @CreateDate:   [2018年10月12日 上午11:51:55]    
 * @Version:      [v1.0]
 */
@Controller
@RequestMapping("/cut")
public class CutController {

	@Resource
	private CutServise cutServise;
	
	@Resource
	private SolidServise solidServise;
	
	@Resource
	private ShedudetailServise shedudetailServise;
	
	/**
	 * 去切割工位撤销页面
	 * @return
	 */
	@RequestMapping("/w5")
	public String toW5() {
		return "/jyy/w5back";
	}
	
	@RequestMapping("/getList")
	public void getList(Cut cut, HttpServletResponse response, 
			@RequestParam(value = "limit",required = false)int limit,
            @RequestParam(value = "page",required = false)int page) throws Exception {
		
		PageHelper.startPage(page, limit);
		
		CutExample example = new CutExample();
		Criteria createCriteria = example.createCriteria();
		
		if(StringUtil.isNotEmpty(cut.getCtube())) {
			createCriteria.andCtubeLike("%"+cut.getCtube()+"%");
		}
		
		List<Cut> list = cutServise.selectByExample(example );
		
		PageInfo<Cut> info = new PageInfo<Cut>(list);
    	
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("code", 0);
        jsonObject.put("msg", "");
        jsonObject.put("count", info.getTotal());
        jsonObject.put("data", info.getList());
        ResponseUtil.write(response, jsonObject);
	}
	
	/**
	 * 进入产品报检页面
	 * @return
	 */
	@RequestMapping("enterProductInspectionPage")
	public String enterProductInspectionPage(){
		return "/jyy/productInspection";
	}
	
	/**
	 * 固化结束，开始切割
	 * @param response
	 * @param cut
	 * @param request
	 * @throws Exception
	 */
	@RequestMapping("/save")
	public void save(HttpServletResponse response, Cut cut, HttpServletRequest request,HttpSession httpSession) throws Exception {
		int insert = 0;
		//插入前验证（该码是否已存在） 存在--》提示     不存在--》添加
		
		CutExample example = new CutExample();
		Criteria createCriteria = example.createCriteria();
		
		if(cut.getCtube() != null && cut.getCtube() != "") {
			createCriteria.andCtubeEqualTo(cut.getCtube());
		}
		
		List<Cut> list = cutServise.selectByExample(example );
		if(list.size() >0) {
			
			//条码存在 且  有结束时间
			if(list.get(0).getCremark() != null && list.get(0).getCremark().trim() != "") {
				insert = -1;
			}else {
				insert = -2;
			}
		}else {
			
			//条码不存在，先判断是否固化结束
			SolidExample example2 = new SolidExample();
			com.sdry.model.jyy.SolidExample.Criteria createCriteria3 = example2.createCriteria();
			createCriteria3.andStubeEqualTo(cut.getCtube());
			//非报废状态
			createCriteria3.andCremark6EqualTo("0");
			List<Solid> list3 = solidServise.selectByExample(example2 );
			if(list3.size() >0) {
				Solid solid2 = list3.get(0);
				String now = DateUtil.dateFormat();
				String starttime = solid2.getStarttime();
				if(starttime != null && starttime != "") {
					String cremark5 = solid2.getCremark5();
					String diff = diff(now,starttime);
					Integer valueOf = Integer.valueOf(diff);
					Integer valueOf2 = Integer.valueOf(cremark5);
					if( valueOf < valueOf2 ) {
						//固化时间没到
						insert = -6;
					}else{
						//此条码不存在  ---》添加，切割开始，固化结束
						String format = DateUtil.dateFormat();
						
						//获取session中的人名
						User people = (User) request.getSession().getAttribute("currentUser");
						
						//截取产品编码
						String tiaoma = cut.getCtube();
						String substring = tiaoma.substring(3, 7);
						
						//固化结束
						SolidExample solidExample = new SolidExample();
						com.sdry.model.jyy.SolidExample.Criteria createCriteria2 = solidExample.createCriteria();
						createCriteria2.andStubeEqualTo(tiaoma);
						List<Solid> solidList = solidServise.selectByExample(solidExample  );
						if(solidList.size() > 0) {
							Solid solid = new Solid();
							
							solid.setId(solidList.get(0).getId());
							solid.setEndtime(format);
							solid.setEndoperator(people.getUserName());
							solid.setCremark8(people.getUid()+"");
							
							//固化结束后，判断台车空了没，空了以后，修改台车状态为0
							String cremark = solidList.get(0).getCremark();
							
							SolidExample example3 = new SolidExample();
							com.sdry.model.jyy.SolidExample.Criteria createCriteria4 = example3.createCriteria();
							if(cremark != "" && cremark != null) {
								createCriteria4.andCremarkEqualTo(cremark);
							}
							
							List<Solid> list4 = solidServise.selectByExample(example3 );
							
							if(list4.size() == 1) {
								solidServise.editTcState0(cremark);
							}
							
							solid.setCremark("");
							insert = solidServise.updateByPrimaryKeySelective(solid);
							
							if(insert == 1) {
								
								String time = "";
								//获取当前班组
								Team team = (Team) httpSession.getAttribute("team");
								//获取当前时间
								String dateFormat1 = DateUtil.dateFormat1();
								
								team.setRemark01(dateFormat1);
								if(team != null) {
									//根据当前时间  当前班组id 查询排产单号
									time = shedudetailServise.selectDaysheduTime(team);
								}
								
								//与排产单对应的时间
								String today = people.getRemark3();
								
								cut.setCremark3(substring);
								cut.setCtime(format);
								cut.setCoperator(people.getUserName());
								cut.setCremark4(people.getUid()+"");
								cut.setCremark6("0");
								cut.setCremark7(today);
								cut.setCplan(time);
								
								cut.setCremark8(team.getTid()+"");
								cut.setCremark9(team.getCrew());
								
								insert = cutServise.insert(cut);
							}else {
								//结束失败
								insert = -3;
							}
						}else {
							//膜管未固化绑定
							insert = -4;
						}
					}
				}else {
					//膜管未开始固化
					insert = -5;
				}
			}else {
				//膜管未开始固化
				insert = -5;
			}
		}
		
		ResponseUtil.write(response, insert);
	}
	
	
	
	
	public String diff(String now, String starttime) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		
		Date now2 = format.parse(now);
		Date starttime2 = format.parse(starttime);
	    long nh = 1000 * 60 * 60;
	    // long ns = 1000;
	    // 获得两个时间的毫秒时间差异
	    long diff = now2.getTime() - starttime2.getTime();
	    // 计算差多少小时
	    long hour = diff / nh;
	    return hour+"";
	}
	
	/**
	 * 切割完成
	 * @param response
	 * @param cut
	 * @param request
	 * @throws Exception
	 */
	@RequestMapping("/edit")
	public void edit(HttpServletResponse response, Cut cut, HttpServletRequest request) throws Exception {
		int insert = 0;
		//插入前验证（该码是否已存在） 存在--》提示     不存在--》添加
		
		CutExample example = new CutExample();
		Criteria createCriteria = example.createCriteria();
		
		if(cut.getCtube() != null && cut.getCtube() != "") {
			createCriteria.andCtubeEqualTo(cut.getCtube());
		}
		
		List<Cut> list = cutServise.selectByExample(example );
		if(list.size() >0) {
			
			for (Cut c : list) {
				//条码存在 且  有结束时间
				if(c.getCremark() != "" && c.getCremark() != null) {
					insert = -1;
				}else {
					//条码存在，且没有结束时间， 修改结束时间
					String format = DateUtil.dateFormat();
					
					cut.setId(c.getId());
					cut.setCremark(format);
					insert = cutServise.updateByPrimaryKeySelective(cut);
				}
			}
		}
		
		ResponseUtil.write(response, insert);
	}
	
	
	/**
	 * 根据产品编码模糊查询产品信息
	 * @param pnum 页面截取的部分产品编码
	 * @param response
	 * @throws Exception 
	 */
	@RequestMapping("/selsectPro")
	public void selsectPro(String pnum,HttpServletResponse response) throws Exception {
		Product product = cutServise.selsectPro(pnum);
		
		//将对象转化为json
		JSONArray json = JSONArray.fromObject(product);
		ResponseUtil.write(response, json);
	}
	
	/**
	 * 根据日期 和产品 编码 统计当日生产量
	 * @param date
	 * @param product
	 * @throws Exception 
	 */
	@RequestMapping("/selectActualNum")
	public void selectActualNum(String product, HttpServletResponse response) throws Exception {
		Cut cut= new Cut();
		
		//String format = DateUtil.dateFormat1();
		
		String time = "";
		
		Date date = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String format = dateFormat.format(date);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Integer now =Integer.parseInt(format.substring(11, 13));
		
		//判断当前时间是7：00之前，还是之后
		
		if(now > 7) {
			time = sdf.format(date);
		}else {
			Calendar ca = Calendar.getInstance();//得到一个Calendar的实例 
			ca.setTime(date); //设置时间为当前时间
			ca.add(Calendar.DATE, -1);
			Date last = ca.getTime();
			time = sdf.format(last);
		}
		
		/*String startTime =format+" 00:00:00";
		String  endTime =format+" 23:59:59";*/
		
		if("PSH2-0960-T-01".equals(product)) {
			product = "0960";
		}else if("PSH2-0980-T-02".equals(product)) {
			product = "0980";
		}else if("PSH1-1060-B-03".equals(product)) {
			product = "1060";
		}else if("PSH1-1080-C-04".equals(product)) {
			product = "1080";
		}
		cut.setCremark3(product);
		//cut.setCremark4(startTime);
		cut.setCremark5(time);
		
		int num = cutServise.selectActualNum(cut);
		ResponseUtil.write(response, num);
	}
	
	/**
	 * 根据日期 和产品 编码 统计当年生产量
	 * @param date
	 * @param product
	 * @throws Exception 
	 */
	@RequestMapping("/selectYearNum")
	public void selectYearNum(String product, HttpServletResponse response) throws Exception {
		Cut cut= new Cut();
		
		Date date = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");
		String format = dateFormat.format(date);
		
		String startTime =format+"-01-01 00:00:0";
		String  endTime =format+"-12-31 23:59:59";
		
		if("PSH2-0960-T-01".contains(product)) {
			product = "0960";
		}else if("PSH2-0980-T-02".contains(product)) {
			product = "0980";
		}else if("PSH1-1060-B-03".contains(product)) {
			product = "1060";
		}else if("PSH1-1080-C-04".contains(product)) {
			product = "1080";
		}
		cut.setCremark3(product);
		cut.setCremark4(startTime);
		cut.setCremark5(endTime);
		
		int num = cutServise.selectYearNum(cut);
		ResponseUtil.write(response, num);
	}
	
	@RequestMapping("/editcremark6")
	public void editcremark6(String code) {
		cutServise.editcremark6(code);
	}
	
	/**
	 * 删除
	 * @param ids
	 * @param response
	 * @throws Exception 
	 */
	@RequestMapping("/delete")
	public void delete(String ids, HttpServletResponse response) throws Exception {
		int affact = cutServise.deleteByPrimaryKeys(ids);
		ResponseUtil.write(response, affact);
	}
	
	/**
	 * 撤销完成（将结束相关字段置空）
	 * @param response
	 * @param cut
	 * @throws Exception 
	 */
	@RequestMapping("/update")
	public void update(HttpServletResponse response, String ids) throws Exception {
		int affact = 0;
		String[] split = ids.split(",");
		for (String s : split) {
			Long id = Long.valueOf(s);
			Cut cut = new Cut();
			cut.setId(id);
			affact = cutServise.updatEnd(id);
		}
		
		ResponseUtil.write(response, affact);
	}
	
	/**
	 * 查询产品报检的台车状态  是否绑定
	 * @param response
	 * @param trolleyNumber 台车条码
	 * @throws Exception 
	 */
	@RequestMapping("/selecTrolley")
	public void selecTrolley(HttpServletResponse response, String trolleyNumber) throws Exception {
		
		int affact = cutServise.selecTrolley(trolleyNumber);
		ResponseUtil.write(response, affact);
		
	}
	
	/**
	 * 验证该膜管是否切割完成
	 * @throws Exception 
	 */
	@RequestMapping("/checkTube")
	public void checkTube(String ctube,HttpServletResponse response) throws Exception {
		
		int affact = 0;
		CutExample example = new CutExample();
		Criteria createCriteria = example.createCriteria();
		
		if(ctube != null && ctube != "") {
			createCriteria.andCtubeEqualTo(ctube);
		}
		createCriteria.andCremarkIsNotNull();
		createCriteria.andCremark6EqualTo("0");
		List<Cut> list = cutServise.selectByExample(example );
		
		if(list.size() >0) {
			//此膜管切割完成
			affact = 1;
			
			/*1.判断此条码是否已绑定台车，或是已报检
			2.已绑定台车，直接提示，已绑定
			3.已报检，判断其是否有反工记录，有返工记录放行，否则，提示已报检
			*/
			
			if(affact == 1) {
				ZcTrolleyBindingEntity zcTrolleyBindingEntity = cutServise.selectBudingByCode(ctube);
				if(zcTrolleyBindingEntity != null) {
					if( "0".equals(zcTrolleyBindingEntity.gettStatus()) ) {
						//绑定
						affact = -1;
					}else {
						//报检
						int count = cutServise.countFgByCode(ctube);
						if(count == 0) {
							//已报检
							affact = -2;
						}//否则，是返工的，放行
					}
				}
			}
		}
		ResponseUtil.write(response, affact);
	}
	
	
}
